package cn.yunyichina.provider.bone.service.impl;

import cn.yunyichina.provider.bone.dao.CooperateOrgDao;
import cn.yunyichina.provider.bone.entity.CooperateOrg;
import cn.yunyichina.provider.bone.vo.ListCooperateOrgRequestVo;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.iface.entity.base.CooperateOrgVo;
import cn.yunyichina.provider.iface.entity.base.Org;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.common.ResponseObject;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.PinyinUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by zd on 2017/4/24.
 * 医院管理
 */
@Service("cooperateorgServiceImpl")
public class CooperateOrgServiceImpl {
    private static final Logger logger = LoggerFactory.getLogger(CooperateOrgServiceImpl.class);
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private CooperateOrgDao cooperateOrgDao;

    private final String PREFIX_ORG = "bone:"; //骨科合作医院前缀

    /**
     * 新增医院
     * @param data
     * @return
     */
    public Response saveCooperateOrg(String data){
        try {
            logger.info("仁医==》新增组织信息开始request："+data);
            CooperateOrgVo request = JsonUtils.parseObject(data,CooperateOrgVo.class);
            if (!checkCooperateOrgVoParameters(request))
                return new Response().buildResultCodeAndMessage("-1", "parameter is error");
            Map<String, String> params = new HashMap<>();
            String orgId = PKGenerator.generateId();
            String orgCode = PREFIX_ORG.concat(PinyinUtils.getChineseFirstWord(request.getCoopOrgName()));
            params.put("id", orgId);
            params.put("org_code",orgCode);
            params.put("org_name",request.getCoopOrgName());
            //二期,区别是平台还是医院
            params.put("org_type", StringUtils.isBlank(request.getOrgType())?"1":request.getOrgType());
            Response response = BaseService.callHumpFromInternal("yyt.base.org.add", JsonUtils.toJsonString(params));
            if (!"0".equals(response.getResultCode())){
                return response;
            }
            Org org = JSONObject.parseObject(response.getResult(),Org.class);
            logger.info("查询到的组织信息 org ={}",new Object[]{JsonUtils.toJsonString(org)});
            CooperateOrg dbCooperateOrg = cooperateOrgDao.selectByCode(org.getOrgCode());
            if (dbCooperateOrg != null){
                logger.info("骨科合作医院已经存在");
                return new  Response("-1","骨科合作医院已经存在");
            }
            logger.info("仁医==》新增组织信息结束");
            logger.info("仁医==》新增骨科合作医院开始");
            CooperateOrg cooperateOrg = new CooperateOrg();
            cooperateOrg.setId(PKGenerator.generateId());
            cooperateOrg.setCoopOrgId(org.getId());
            cooperateOrg.setCoopOrgCode(orgCode);
            cooperateOrg.setCoopOrgName(request.getCoopOrgName());
            cooperateOrg.setCoopProvinceId(request.getCoopProvinceId());
            cooperateOrg.setCoopProvinceName(request.getCoopProvinceName());
            cooperateOrg.setCoopCityId(request.getCoopCityId());
            cooperateOrg.setCoopCityName(request.getCoopCityName());
            cooperateOrg.setHospitalLevel(request.getHospitalLevel());
            cooperateOrg.setWeight(Integer.valueOf(request.getWeight()));
            cooperateOrg.setHospitalImg(request.getHospitalImg());
            cooperateOrg.setSurgeryConditionInfo(request.getSurgeryConditionInfo());
            //二期cooperateOrg
            if (request.getOrgType()!=null){
                cooperateOrg.setCoopOrgType(Short.valueOf(request.getOrgType()));
            }
            cooperateOrg.setCreatedTime(simpleDateFormat.format(new Date()));
            cooperateOrgDao.insert(cooperateOrg);
            logger.info("仁医==》新增骨科合作医院结束");
            return Response.success();
        }catch (Exception e){
            logger.error("新增骨科合作医院失败",e);
            return Response.failure();
        }

    }

    protected boolean checkCooperateOrgVoParameters(CooperateOrgVo request) {
        if (StringUtils.isEmpty(request.getCoopProvinceId().trim())||StringUtils.isEmpty(request.getHospitalLevel().trim())
                ||StringUtils.isEmpty(request.getCoopOrgName().trim())||StringUtils.isEmpty(request.getWeight().trim())
                ||StringUtils.isEmpty(request.getCoopCityName().trim())||StringUtils.isEmpty(request.getCoopProvinceName().trim())
                ||StringUtils.isEmpty(request.getCoopCityId().trim())) return false;
        return true;
    }
    /**
     * 更新医院手术条件
     * @param data
     * @return
     */
    public ResponseObject updateCooperateOrg(String data){
        ResponseObject responseObject = new ResponseObject();
        try {
            logger.info("CooperateOrgServiceImpl->updateCooperateOrg request data ={}",data);
            CooperateOrgVo requestVo = JsonUtils.parseObject(data,CooperateOrgVo.class);
            if (!checkCooperateOrgVoParameters(requestVo))
                return new ResponseObject().buildResultCodeAndMessage("-1", "parameter is error");
            CooperateOrg dbCooperateOrg_var1 = cooperateOrgDao.selectById(requestVo.getId());
            if(dbCooperateOrg_var1!=null) {
                if (!dbCooperateOrg_var1.getCoopOrgName().equals(requestVo.getCoopOrgName())) {
                    CooperateOrg dbCooperateOrg_var2 = cooperateOrgDao.selectByCode(PREFIX_ORG.concat(PinyinUtils.
                            getChineseFirstWord(requestVo.getCoopOrgName())));
                    if (dbCooperateOrg_var2 != null) {
                        logger.info("CooperateOrgServiceImpl->通过coop_org_code:{},返回CooperateOrg:{}",
                                PREFIX_ORG.concat(PinyinUtils.getChineseFirstWord(requestVo.getCoopOrgName())), JSON.toJSONString(dbCooperateOrg_var2));
                        responseObject.setResultCodeAndMessage("1", "cooperateOrg is exit");
                        return responseObject;
                    }
                }
            } else {
                responseObject.setResultCodeAndMessage("1","cooperateOrg is null");
                return responseObject;
            }
            CooperateOrg cooperateOrg = new CooperateOrg();
            BeanUtils.copyProperties(requestVo, cooperateOrg);
            cooperateOrg.setWeight(Integer.valueOf(requestVo.getWeight()));
            cooperateOrg.setCoopOrgCode(PREFIX_ORG.concat(PinyinUtils.getChineseFirstWord(requestVo.getCoopOrgName())));
            cooperateOrgDao.update(cooperateOrg);
            responseObject.setResultCodeAndMessage("0","success");
            return responseObject;
        }catch (Exception e){
            logger.error("update hospital failure",e );
            responseObject.setResultCodeAndMessage("-1","update hospital information exception");
            return responseObject;
        }
    }

    /**
     * 查询医院列表
     * @param
     * @return
     */
    public ResponseObject listCooperateOrg(String data){
        ResponseObject response = new ResponseObject();
        try {
            logger.info("查询医院列表->CooperateOrgServiceImpl->listCooperateOrg request data ={}",data);
            Map<String ,Object> resultMap = new HashMap<String ,Object>();
            ListCooperateOrgRequestVo requestVo = JsonUtils.parseObject(data, ListCooperateOrgRequestVo.class);
            Map<String ,Object> map = new HashMap<String ,Object>();
            if (requestVo.getPageSize() != null) {
                map.put("pageSize", requestVo.getPageSize().intValue());
            }
            if (requestVo.getPageNum() != null) {
                map.put("pageNum", requestVo.getPageNum());
            }
            if (requestVo.getCoopOrgName() != null){
                map.put("orgName",requestVo.getCoopOrgName());
            }
            if (requestVo.getOrgType() != null){
                map.put("coopOrgType",requestVo.getOrgType());
            }
            if(requestVo.getCoopProvinceId()!=null){
                map.put("coopProvinceId",requestVo.getCoopProvinceId());
            }
            if(requestVo.getCoopCityId()!=null){
                map.put("coopCityId",requestVo.getCoopCityId());
            }
            List<Map<String, Object>> datas = cooperateOrgDao.selectCooperateOrg(map);
            List<Map<String,String>> groupByCity=cooperateOrgDao.groupByCity();
            resultMap.put("datas", datas);
            resultMap.put("groupByCity",groupByCity);
            //CooperateOrg wheres = new CooperateOrg();
            // wheres.setCoopOrgName(requestVo.getCoopOrgName());
            map.remove("pageSize");
            map.remove("pageNum");
            long datasCount = cooperateOrgDao.selectCooperateOrg(map).size();
            resultMap.put("datasCount",datasCount);
            logger.info("查询医院列表->CooperateOrgServiceImpl->listCooperateOrg response data ={}",JSON.toJSONString(resultMap));
            response.setResultCodeAndMessageAndResult("0","成功",JsonUtils.toJsonString(resultMap));
        }catch (Exception e){
            logger.error("查询医院出错",e);
            response.setResultCodeAndMessage("-1","查询医院出错");
        }
        return response;
    }

    /**
     * 根据id查询bone_cooperate_org(骨科合作的医院)组织<br>
     * yyt.bone.cooperateorg.by.id.find
     * @param orgId
     * @return
     */
    public Response findCooperateOrgById(String data) {
        logger.info("CooperateOrgServiceImpl->findCooperateOrgById request data ={}",data);
        String coooperId=null;
        if (data.startsWith("{")) {
            JSONObject param = JsonUtils.parseObject(data);
            coooperId = param.getString("id");
            if (StringUtils.isBlank(coooperId)) {
                coooperId = param.getString("org_id");
            }
        }
        Response response = new Response();
        CooperateOrg cooperateOrg = cooperateOrgDao.selectById(coooperId);
        logger.info("CooperateOrgServiceImpl->findCooperateOrgById reponse data ={}", JSON.toJSONString(cooperateOrg));
        response.setResult(JsonUtils.toJsonString(cooperateOrg));
        response.setResultCodeAndMessage("0", "查询成功!");
        return response;

    }

}
